import { useState, useRef } from "react";
import { useQueryClient, useMutation } from 'react-query';
import { faEdit, faPlus, faSave } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { formatDateTime } from "@/tools/data-helpers";
import { updateChapterNameById, createChapterByCourseId } from "@/apis/chapter";
import { chapters } from "@/mock/chapter";


/**
 * This component use react-Query mutaion.
 * More details see: https://react-query.tanstack.com/guides/invalidations-from-mutations
 */
function ChapterItem({ chapter, courseId, isCourseManager }) {
    const queryClient = useQueryClient();

    const mutateChapter = useMutation(updateChapterNameById, {
        onSuccess: () => {
            queryClient.invalidateQueries('chapters');
        },
    });
    const createChapter = useMutation(createChapterByCourseId, {
        onSuccess: () => {
            queryClient.invalidateQueries('chapters');
        },
    });

    const [isEditable, setIsEditable] = useState(false);
    const [isCreating, setIsCreating] = useState(false);

    const changeRef = useRef(null);
    const createRef = useRef(null);

    function handleEdit(e) {
        e.preventDefault();
        setIsEditable(true);
    }

    function handleChange(e) {
        e.preventDefault();
        setIsEditable(false);
        const newChapterName = changeRef.current.value;
        if (newChapterName !== chapter.name) {
            mutateChapter.mutate({
                newChapterName,
                chapterId: chapter.id,
                courseId,
            });
        }
    }

    function handleCreate(e) {
        e.preventDefault();
        setIsCreating(true);
    }

    function handleSave(e) {
        e.preventDefault();
        setIsCreating(false);
        const chapterName = createRef.current.value;

        createChapter.mutate({
            chapterName,
            courseId,
            currentChapter: chapter
        });
    }

    return (
        <li className="my-4" key={chapter && chapter.id}>
            {!isEditable &&
                <div className="row align-items-center">
                    <a className="col-md-3 ms-2 fw-bold" href={`/course/${courseId}/chapter/${chapter.id}`}>{chapter && chapter.name}</a>
                    <small className="col-md-3">{chapter && formatDateTime(chapter.updated_time)}</small>
                    <div className="col-md-1">
                        {(isCourseManager && !isCreating) &&
                            <div className="row">
                                <button className="col  btn btn-outline-secondary btn-sm p-0 mx-1" onClick={handleEdit}><FontAwesomeIcon icon={faEdit} /></button>
                                <button className="col btn btn-outline-secondary btn-sm p-0" onClick={handleCreate}><FontAwesomeIcon icon={faPlus} /></button>
                            </div>
                        }
                    </div>
                </div>
            }
            {isEditable &&
                <div className="row align-items-center">
                    <div className="col-md-9">
                        <div className="input-group ms-2">
                            <input className="form-control" ref={changeRef} type="text" placeholder={chapter && chapter.name} />
                        </div>
                    </div>
                    <div className="col-md-1">
                        <div className="row">
                            <button className="col  btn btn-outline-secondary btn-sm" onClick={handleChange}>保存</button>
                        </div>
                    </div>
                </div>
            }
            {isCreating &&
                <div className="row align-items-center">
                    <div className="col-md-9">
                        <div className="input-group ms-2">
                            <input className="form-control" ref={createRef} type="text" placeholder={chapter && chapter.name} />
                        </div>
                    </div>
                    <div className="col-md-1">
                        <div className="row">
                            <button type="button" className="btn btn-outline-secondary btn-sm" onClick={handleSave}>新建</button>
                        </div>
                    </div>
                </div>
            }
        </li>
    )
}

function ChapterCreator({ courseId }) {
    const queryClient = useQueryClient();
    const createRef = useRef(null);
    const createChapter = useMutation(createChapterByCourseId, {
        onSuccess: () => {
            queryClient.invalidateQueries('chapters');
        },
    });
    function handleSave(e) {
        e.preventDefault();
        const chapterName = createRef.current.value;

        createChapter.mutate({
            chapterName,
            courseId,
        });
    }
    return (
        <div className="row align-items-center">
            <div className="col-md-9">
                <div className="input-group ms-2">
                    <input className="form-control" ref={createRef} type="text" placeholder="还没有章节，新建一个" />
                </div>
            </div>
            <div className="col-md-1">
                <div className="row">
                    <button type="button" className="btn btn-outline-secondary btn-sm" onClick={handleSave}>新建</button>
                </div>
            </div>
        </div>
    )
}

export default function CourseChapterList({ courseId, chapters, isCourseManager }) {
    const chapterArray = chapters || [];

    const chapterItems = chapterArray.map((chapter) => (
        <ChapterItem key={chapter && chapter.id} courseId={courseId} chapter={chapter} isCourseManager={isCourseManager} />
    ));

    return (
        <ol className="col-md-10">
            {chapterArray.length === 0 &&
                <ChapterCreator courseId={courseId} />
            }
            {chapterItems}
        </ol>
    );
};
